import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const Login = () => import("../views/Login")
const Layout = () => import("../views/Layout")

const Home = () => import("../views/Home")
const Menus = () => import("../views/system/Menus")
const Roles = () => import("../views/system/Roles")
const Managers = () => import("../views/system/Manager")

const Cate = () => import("../views/goods/Cate")

const routes = [
  {
    path: '/',
    redirect: "/login"
  },
  {
    path: "/login",
    component: Login,
    meta: {
      title: "管理员登录"
    }
  },
  {
    path: "/main",
    component: Layout,
    redirect: "/main/home",
    children: [
        {
          path: "home",
          component: Home,
          meta: {
          title: "管理中心"
          }
        },
        {
          path: "menu",
          component: Menus,
          meta: {
            title: "菜单管理"
          }
        },
        {
          path: "role",
          component: Roles,
          meta: {
            title: "角色管理"
          }
        },
        {
          path: "manager",
          component: Managers,
          meta: {
            title: "管理员管理"
          }
        },
        {
          path: "cate",
          component: Cate,
          meta: {
            title: "分类管理"
          }
        }
    ]
  },
]

const router = new VueRouter({
  routes
})

// 全局前置导航守卫：完成未登录用户的拦截
router.beforeEach( (to,from,next) => {
  console.log(to,from);
  if(to.path !== "/login") {
    // 是否登录认证？
    let adminInfo = JSON.parse(localStorage.getItem("adminInfo")||'{}')
    if(!adminInfo.token) {
      // next()函数表示请求向后传递
      // 如果给next(path)给定一个路径，就会自动重定向到这个路径
      return next("/login")
    }
  }
  next()
})

// 全局解析守卫
router.beforeResolve( (to,from,next) => {
  console.log(to,from);
  // 给组件页面添加标题
  document.title = to.meta.title
  next()
})


export default router
